<?php

namespace Biz\service\SuperSubsidy;

use Biz\model\SuperSubsidy\YouZanBrandUserModel;
use Biz\model\SuperSubsidy\YouZanBrandGoodsModel;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\newCache;

class YouZanGoods implements ConstInterface
{

    public static function brandCreateSpu($accountId, $data)
    {
        $goodsCreate = new YouZanGoodsInfo($data);
        $res = $goodsCreate->create($accountId);
        if ($res) {
            sleep(5);
            $res = $goodsCreate->release();
        }
        return $res;
    }

    public static function brandSpuRelease($spuCode, $data)
    {
        $goodsCreate = new YouZanGoodsInfo($data, $spuCode);
        $res = $goodsCreate->release();
        return $res;
    }

    public static function brandUpdateSpu($id, $data)
    {
        $info = YouZanBrandGoodsModel::getByWhere(['id' => $id]);
        if (!$info) {
            throw new \Exception('不存在的信息');
        }
        $addData = [
            'name' => $data['name'],
            'photo_url' => $data['photo_url'],
            'category_id' => $data['category_id'],
            'white_img' => $data['white_img'],
            'video_info' => $data['video_info'],
            'sell_point' => $data['sell_point'],
            'goods_service' => $data['goods_service'],
            'content' => $data['content'],
            'no_sku_info' => json_encode($data['no_sku_info']),
            'sku_info' => json_encode($data['sku_info']),
            'status' => YouZanBrandGoodsModel::STATUS_WAIT_UPDATED
        ];
        $res = YouZanBrandGoodsModel::updateData($addData, ['id' => $info['id']]);
        if ($res) {
            return true;
        } else {
            throw new \Exception('创建商品失败');
        }
    }

    public static function getGoodsList($accountId, $page = 1, $pageSize = 20)
    {
        $list = [];
        $where = [
            'brand_user_id' => $accountId,
            'LIMIT' => [($page - 1) * $pageSize, $pageSize],
            'ORDER' => ['id' => 'DESC']
        ];
        $res = YouZanBrandGoodsModel::selectByWhere($where);
        foreach ($res as $row) {
            $noSkuInfo = $row['no_sku_info'] ? json_decode($row['no_sku_info'], true) : [];
            $sku_info = $row['sku_info'] ? json_decode($row['sku_info'], true) : [];
            $item = [
                'id' => $row['id'],
                'spu_code' => $row['spu_code'],
                'name' => $row['name'],
                'supply_price' => '',
                'min_price' => '',
                'total_stock' => '',
                'created_at' => $row['created_at'],
                'status' => $row['status'],
                'status_desc' => YouZanBrandGoodsModel::STATUS_MAP[$row['status']],
            ];
            if ($sku_info) {
                $skus = json_decode($sku_info['skus'], true);
                $item['supply_price'] = $skus[0]['supply_price'] ?? '';
                $item['min_price'] = $skus[0]['min_price'] ?? '';
                $item['total_stock'] = $skus[0]['stock'] ?? '';
            } else {
                $item['supply_price'] = $noSkuInfo['supply_price'];
                $item['min_price'] = $noSkuInfo['min_price'];
                $item['total_stock'] = $noSkuInfo['total_stock'];
            }
            $list[] = $item;
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = YouZanBrandGoodsModel::selectCountWhere($where);
        $isOver = ($page * $pageSize) >= $count ? 1 : 0;
        return ['list' => $list, 'count' => $count, 'is_over' => $isOver];
    }

    public static function getGoodsInfo($id)
    {
        $info = [];
        $res = YouZanBrandGoodsModel::getByWhere(['id' => $id]);
        if ($res) {
            $photoUrlArr = json_decode($res['photo_url'], true);
            $photoUrl = [];
            foreach ($photoUrlArr as $row) {
                $photoUrl[] = [
                    'image_url' => $row['url'],
                    'image_id' => $row['id'],
                    'height' => $row['height'] ?? "",
                    'width' => $row['width'] ?? "",
                ];
            }
            $noSkuInfo = $res['no_sku_info'] ? json_decode($res['no_sku_info'], true) : [];
            $sku_info = $res['sku_info'] ? json_decode($res['sku_info'], true) : [];
            $info = [
                'id' => $id,
                'name' => $res['name'],
                'category_id' => $res['category_id'],
                'photo_url' => $photoUrl,
                'white_img' => $res['white_img'] ? json_decode($res['white_img'], true) : null,
                'video_info' => $res['video_info'] ? json_decode($res['video_info'], true) : null,
                'sell_point' => $res['sell_point'],
                'content' => $res['content'] ? json_decode($res['content'], true) : [],
                'goods_service' => $res['goods_service'],
                //无规格字段
                'supply_price' => $noSkuInfo['supply_price'] ?? '',
                'market_price' => $noSkuInfo['market_price'] ?? '',
                'min_price' => $noSkuInfo['min_price'] ?? '',
                'item_weight' => $noSkuInfo['item_weight'] ?? '',
                'total_stock' => $noSkuInfo['total_stock'] ?? '',
                'status' => $res['status'],
                'status_desc' => YouZanBrandGoodsModel::STATUS_MAP[$res['status']],
            ];
            if ($sku_info) {
                //有规格字段
                $info['sku_specs'] = json_decode($sku_info['sku_specs'], true);
                $info['skus'] = json_decode($sku_info['skus'], true);
            }
        }
        return $info;
    }

    public static function getBrandGoodsList($where)
    {
        $goodsList = YouZanBrandGoodsModel::selectByWhere($where);
        $brandUserIds = $goodsList ? array_column($goodsList, 'brand_user_id') : [];
        $brandUserList = $brandUserIds ? YouZanBrandUserModel::selectByWhere(['id' => $brandUserIds]) : [];
        $brandUserList = $brandUserList ? array_column($brandUserList, null, 'id') : [];
        $list = [];
        foreach ($goodsList as $row) {
            $photoUrlArr = json_decode($row['photo_url'], true);
            $photoUrl = [];
            foreach ($photoUrlArr as $urlItem) {
                $photoUrl[] = $urlItem['url'];
            }
            $cover_img = $photoUrl[0] ?? '';
            $noSkuInfo = $row['no_sku_info'] ? json_decode($row['no_sku_info'], true) : [];
            $sku_info = $row['sku_info'] ? json_decode($row['sku_info'], true) : [];
            $item = [
                'id' => $row['id'],
                'brand_user_id' => $row['brand_user_id'],
                'brand_name' => $brandUserList[$row['brand_user_id']]['brand_name'] ?? '',
                'spu_code' => $row['spu_code'],
                'spu_no' => $row['spu_no'],
                'item_id' => $row['item_id'],
                'name' => $row['name'],
                'cover_img' => $cover_img,
                'photo_url' => $photoUrl,
                'white_img' => $row['white_img'] ? json_decode($row['white_img'], true) : [],
                'goods_service' => $row['goods_service'],
                'supply_price' => '',
                'market_price' => '',
                'min_price' => '',
                'total_stock' => '',
                'created_at' => $row['created_at'],
                'update_at' => $row['update_at'],
                'status' => $row['status'],
                'status_desc' => YouZanBrandGoodsModel::STATUS_MAP[$row['status']],
                'sku_info' => $sku_info,
                'no_sku_info' => $noSkuInfo,
            ];
            if ($sku_info) {
                $skus = json_decode($sku_info['skus'], true);
                $item['supply_price'] = $skus[0]['supply_price'] ?? '';
                $item['market_price'] = $skus[0]['market_price'] ?? '';
                $item['min_price'] = $skus[0]['min_price'] ?? '';
                $item['total_stock'] = $skus[0]['stock'] ?? '';
                $item['sku_specs'] = json_decode($sku_info['sku_specs'], true);
                $item['skus'] = $skus;
            } else {
                $item['supply_price'] = $noSkuInfo['supply_price'];
                $item['market_price'] = $noSkuInfo['market_price'] ?? '';
                $item['min_price'] = $noSkuInfo['min_price'];
                $item['total_stock'] = $noSkuInfo['total_stock'];
            }
            $list[] = $item;
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = YouZanBrandGoodsModel::selectCountWhere($where);
        return [$list, $count];
    }

    public static function getBrandGoodsInfo($id)
    {
        $goodsInfo = YouZanBrandGoodsModel::getByWhere(['id' => $id]);
        $brandUserId = $goodsInfo['brand_user_id'];
        $brandUserInfo = $brandUserId ? YouZanBrandUserModel::getByWhere(['id' => $brandUserId]) : [];

        $photoUrlArr = json_decode($goodsInfo['photo_url'], true);
        $photoUrl = [];
        foreach ($photoUrlArr as $urlItem) {
            $photoUrl[] = $urlItem['url'];
        }
        $noSkuInfo = $goodsInfo['no_sku_info'] ? json_decode($goodsInfo['no_sku_info'], true) : [];
        $sku_info = $goodsInfo['sku_info'] ? json_decode($goodsInfo['sku_info'], true) : [];
        $goodsServiceArr = explode(',', $goodsInfo['goods_service']);
        $goodsService = [];
        if ($goodsServiceArr) {
            foreach ($goodsServiceArr as $row) {
                $goodsService[] = YouZanBrandGoodsModel::GOODS_SERVICE_MAP[$row];
            }
        }
        $categoryArr = [];
        self::getCategoryStr($categoryArr, $goodsInfo['category_id']);
        krsort($categoryArr);
        $info = [
            'id' => $goodsInfo['id'],
            'brand_user_id' => $goodsInfo['brand_user_id'],
            'brand_name' => $brandUserInfo['brand_name'] ?? '',
            'spu_code' => $goodsInfo['spu_code'],
            'spu_no' => $goodsInfo['spu_no'],
            'item_id' => $goodsInfo['item_id'],
            'name' => $goodsInfo['name'],
            'photo_url' => $photoUrl,
            'category_id' => $goodsInfo['category_id'],
            'category' => $categoryArr ? implode('>>', $categoryArr) : [],
            'white_img' => $goodsInfo['white_img'] ? json_decode($goodsInfo['white_img'], true) : [],
            'goods_service' => implode('，', $goodsService),
            'content' => $goodsInfo['content'] ? json_decode($goodsInfo['content'], true) : [],
            'supply_price' => '',
            'market_price' => '',
            'min_price' => '',
            'total_stock' => '',
            'created_at' => $goodsInfo['created_at'],
            'status' => $goodsInfo['status'],
            'status_desc' => YouZanBrandGoodsModel::STATUS_MAP[$goodsInfo['status']],
            'sku_info' => $sku_info,
            'no_sku_info' => $noSkuInfo,
        ];
        if ($sku_info) {
            $skus = json_decode($sku_info['skus'], true);
            $info['supply_price'] = $skus[0]['supply_price'] ?? '';
            $info['market_price'] = $skus[0]['market_price'] ?? '';
            $info['min_price'] = $skus[0]['min_price'] ?? '';
            $info['total_stock'] = $skus[0]['stock'] ?? '';
            $info['sku_specs'] = json_decode($sku_info['sku_specs'], true);
            $info['skus'] = $skus;
        } else {
            $info['supply_price'] = $noSkuInfo['supply_price'];
            $info['market_price'] = $noSkuInfo['market_price'] ?? '';
            $info['min_price'] = $noSkuInfo['min_price'];
            $info['total_stock'] = $noSkuInfo['total_stock'];
        }
        return $info;
    }

    private static function getCategoryStr(&$result, $categoryId, array $allCategory = [])
    {
        if (!$allCategory) {

            $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_SPU_CATEGORY);
            $allCategory = $redis->getCache();

            $allCategory = array_column($allCategory, null, 'category_id');
        }
        $categoryInfo = $allCategory[$categoryId] ?? [];
        if ($categoryInfo) {
            array_push($result, $categoryInfo['name']);
            if ($categoryInfo['parent_id'] > 0) {
                self::getCategoryStr($result, $categoryInfo['parent_id'], $allCategory);
            }
        }
    }

}
